<template>
  <div class="pd-report">
    <div class="toolbar">
      <el-radio-group v-model="quickRange" size="small" @change="onQuickRange">
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="yesterday">昨日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="custom">自定义</el-radio-button>
      </el-radio-group>
      <el-date-picker v-model="dateRange" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :disabled="quickRange !== 'custom'" style="margin-left:12px;width:420px" />
      <el-input v-model="query.warehouseName" placeholder="仓库名称" style="width:160px;margin-left:12px" clearable />
      <el-input v-model="query.goodsOrCategory" placeholder="物品/类别" style="width:160px;margin-left:12px" clearable />
      <el-button type="primary" style="margin-left:12px" @click="loadData(1)">生成报表</el-button>
      <el-button @click="reset">重置</el-button>
    </div>

    <div class="cards">
      <el-card class="card" shadow="never"><div class="num">{{ stats.count }}</div><div class="desc">盘点次数</div></el-card>
      <el-card class="card" shadow="never"><div class="num">{{ stats.totalQuantity }}</div><div class="desc">盘点总数量</div></el-card>
      <el-card class="card" shadow="never"><div class="num green">{{ stats.profitQuantity }}</div><div class="desc">盘盈数量</div></el-card>
      <el-card class="card" shadow="never"><div class="num orange">{{ stats.lossQuantity }}</div><div class="desc">盘亏数量</div></el-card>
      <el-card class="card" shadow="never"><div class="num green">{{ formatMoney(stats.profitAmount) }}</div><div class="desc">盘盈成本总额</div></el-card>
      <el-card class="card" shadow="never"><div class="num orange">{{ formatMoney(stats.lossAmount) }}</div><div class="desc">盘亏成本总额</div></el-card>
      <el-card class="card" shadow="never"><div class="num">{{ (stats.accuracyRate*100).toFixed(2) }}%</div><div class="desc">准确率</div></el-card>
    </div>

    <el-table :data="tableData" border style="width:100%" height="560">
      <el-table-column type="index" label="#" width="60" />
      <el-table-column prop="billNo" label="盘点单号" width="140" />
      <el-table-column prop="startTime" label="开始时间" width="170"><template #default="{ row }">{{ formatTime(row.startTime) }}</template></el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="170"><template #default="{ row }">{{ formatTime(row.endTime) }}</template></el-table-column>
      <el-table-column prop="warehouseName" label="仓库名称" width="140" />
      <el-table-column prop="inventoryResult" label="盘点结果" width="100" />
      <el-table-column prop="goodsName" label="货品名称" min-width="180" />
      <el-table-column prop="quantity" label="盘点数量" width="100" />
      <el-table-column prop="profitQuantity" label="盘盈数量" width="100" />
      <el-table-column prop="lossQuantity" label="盘亏数量" width="100" />
      <el-table-column prop="profitAmount" label="盘盈金额" width="120"><template #default="{ row }">{{ formatMoney(row.profitAmount) }}</template></el-table-column>
      <el-table-column prop="lossAmount" label="盘亏金额" width="120"><template #default="{ row }">{{ formatMoney(row.lossAmount) }}</template></el-table-column>
      <el-table-column prop="makerName" label="制单人" width="100" />
      <el-table-column prop="deptName" label="所在部门" width="120" />
      <el-table-column prop="makeTime" label="制单时间" width="170"><template #default="{ row }">{{ formatTime(row.makeTime) }}</template></el-table-column>
      <el-table-column prop="remark" label="备注" min-width="160" />
    </el-table>

    <div class="pager">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total" :page-sizes="[10,20,50,100]" v-model:current-page="page" v-model:page-size="pageSize" @size-change="loadData(1)" @current-change="loadData" />
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { ref, reactive, watch } from 'vue'
import { fetchStocktakingPage, fetchStocktakingStats, type GetStocktakingInput } from '/@/api/report/pd'

const tableData = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const quickRange = ref<'today'|'yesterday'|'week'|'month'|'custom'>('month')
const dateRange = ref<[string,string]|null>(null)

const query = reactive<{ warehouseName?: string; goodsOrCategory?: string }>({})

function computeRange() {
  const now = dayjs()
  switch (quickRange.value) {
    case 'today': return [now.startOf('day').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'yesterday': { const y = now.subtract(1,'day'); return [y.startOf('day').format('YYYY-MM-DD HH:mm:ss'), y.endOf('day').format('YYYY-MM-DD HH:mm:ss')] }
    case 'week': return [now.startOf('week').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'month': return [now.startOf('month').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    default: return dateRange.value ?? null
  }
}

function buildPayload(p = page.value): GetStocktakingInput {
  const range = computeRange()
  return {
    startTime: range?.[0],
    endTime: range?.[1],
    warehouseName: query.warehouseName,
    goodsOrCategory: query.goodsOrCategory,
    page: p,
    pageSize: pageSize.value,
  }
}

async function loadData(p?: number) {
  if (p) page.value = p
  const payload = buildPayload()
  const [pageRes, statsRes] = await Promise.all([
    fetchStocktakingPage(payload),
    fetchStocktakingStats(payload),
  ])
  
  console.log('Page response:', pageRes)
  console.log('Stats response:', statsRes)
  
  // 根据图片格式：data.result.result.items（两层result）
  const pageData = pageRes?.data?.result?.result
  if (pageData) {
    tableData.value = pageData.items || []
    total.value = pageData.total || 0
  } else {
    tableData.value = []
    total.value = 0
  }
  
  // 统计数据：data.result.result
  const statsData = statsRes?.data?.result?.result
  if (statsData) {
    stats.value = {
      count: statsData.count || 0,
      totalQuantity: statsData.totalQuantity || 0,
      profitQuantity: statsData.profitQuantity || 0,
      lossQuantity: statsData.lossQuantity || 0,
      profitAmount: statsData.profitAmount || 0,
      lossAmount: statsData.lossAmount || 0,
      accuracyRate: statsData.accuracyRate || 0,
    }
  } else {
    stats.value = {
      count: 0,
      totalQuantity: 0,
      profitQuantity: 0,
      lossQuantity: 0,
      profitAmount: 0,
      lossAmount: 0,
      accuracyRate: 0,
    }
  }
}

function reset() {
  quickRange.value = 'month'
  dateRange.value = null
  query.warehouseName = undefined
  query.goodsOrCategory = undefined
  loadData(1)
}

function onQuickRange() {
  if (quickRange.value !== 'custom') dateRange.value = null
  loadData(1)
}

const stats = ref({ count: 0, totalQuantity: 0, profitQuantity: 0, lossQuantity: 0, profitAmount: 0, lossAmount: 0, accuracyRate: 1 })

function formatMoney(n: number) { return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY', maximumFractionDigits: 2 }).format(n || 0) }
function formatTime(t: string | Date) { if (!t) return ''; const d = typeof t === 'string' ? new Date(t) : t; return dayjs(d).format('YYYY-MM-DD HH:mm:ss') }

watch(pageSize, () => loadData(1))

loadData(1)
</script>

<style scoped>
.pd-report { padding: 12px; }
.toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.cards { display: grid; grid-template-columns: repeat(7, 1fr); gap: 12px; margin: 12px 0; }
.card { text-align: center; }
.num { font-size: 22px; font-weight: 700; }
.num.green { color: #18a058; }
.num.orange { color: #f0a020; }
.desc { color: #888; margin-top: 4px; font-size: 12px; }
.pager { margin-top: 10px; display: flex; justify-content: flex-end; }
</style>


